﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace ToyStore.Domain.Common
{
	/// <summary>
	/// Klasa pomocnicza wyciagajaca z Linq expression nazwe propertisa przekazanego.
	/// </summary>
	public static class PropertySupport
	{
		/// <summary>
		/// Metoda wyciagajaca nazwe propertisa.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="propertyExpression"></param>
		/// <returns></returns>
		public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
		{
			if (propertyExpression == null)
			{
				throw new ArgumentNullException("propertyExpression");
			}
			var memberExpression = propertyExpression.Body as MemberExpression;
			if (memberExpression == null)
			{
				throw new ArgumentException("Something is wrong!");
			}
			var property = memberExpression.Member as PropertyInfo;
			if (property == null)
			{
				throw new ArgumentException("Something is wrong!");
			}
			if (property.GetGetMethod(true).IsStatic)
			{
				throw new ArgumentException("Something is wrong!");
			}
			return memberExpression.Member.Name;
		}
	}
}
